#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
导入对话框界面
"""

from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, 
                             QPushButton, QProgressBar, QLabel, QMessageBox)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import traceback
from bill_converter import convert_bill, BillConverter
from database import Database


class ImportWorker(QThread):
    """导入工作线程"""
    progress = pyqtSignal(int)  # 进度信号
    finished = pyqtSignal(list)  # 完成信号
    error = pyqtSignal(str)      # 错误信号
    
    def __init__(self, file_path):
        super().__init__()
        self.file_path = file_path
        
    def run(self):
        """执行导入任务"""
        try:
            print(f"开始解析文件: {self.file_path}")
            # 使用统一账单格式转换引擎
            transactions = convert_bill(self.file_path)
            bill_type = BillConverter().detect_bill_type(self.file_path)
            print(f"{bill_type}文件解析完成，共获得{len(transactions)}条交易记录")
            self.finished.emit(transactions)
        except Exception as e:
            error_info = f"解析文件时出错: {str(e)}\n文件路径: {self.file_path}\n详细错误信息: {traceback.format_exc()}"
            print(error_info)
            self.error.emit(error_info)


class ImportDialog(QDialog):
    def __init__(self, file_path, parent=None):
        super().__init__(parent)
        self.file_path = file_path
        self.transactions = []
        self.db = Database()
        self.init_ui()
        self.start_import()
        
    def init_ui(self):
        """初始化界面"""
        # 使用统一账单格式转换引擎设置窗口标题
        bill_type = BillConverter().detect_bill_type(self.file_path)
        if bill_type == 'alipay':
            self.setWindowTitle('导入支付宝账单')
        elif bill_type == 'wechat':
            self.setWindowTitle('导入微信账单')
        elif bill_type == 'bank':
            self.setWindowTitle('导入银行账单')
        else:
            self.setWindowTitle('导入账单')
        
        layout = QVBoxLayout()
        
        # 显示账单类型信息
        self.info_label = QLabel(f"检测到账单类型: {bill_type}")
        self.info_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.info_label)
        self.setModal(True)
        self.resize(400, 150)
        
        # 状态标签
        self.status_label = QLabel('正在解析文件...')
        self.status_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.status_label)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        layout.addWidget(self.progress_bar)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
        
    def start_import(self):
        """开始导入"""
        self.worker = ImportWorker(self.file_path)
        self.worker.progress.connect(self.update_progress)
        self.worker.finished.connect(self.on_import_finished)
        self.worker.error.connect(self.on_import_error)
        self.worker.start()
        
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)
        
    def on_import_finished(self, transactions):
        """导入完成"""
        self.transactions = transactions
        self.status_label.setText(f'解析完成，共{len(transactions)}条记录，正在保存...')
        self.save_to_database()
        
    def on_import_error(self, error_msg):
        """导入错误"""
        # 记录详细的错误信息到控制台
        print(f"导入错误详情: {error_msg}")
        QMessageBox.critical(self, '导入失败', f'导入过程中出现错误：\n{error_msg}')
        self.reject()
        
    def save_to_database(self):
        """保存到数据库"""
        try:
            # 准备批量插入的数据
            transaction_data = []
            for transaction in self.transactions:
                try:
                    transaction_data.append((
                        transaction.timestamp,
                        transaction.amount,
                        transaction.type,
                        transaction.category,
                        transaction.payee,
                        transaction.source,
                        transaction.note
                    ))
                except Exception as e:
                    # 记录错误但继续处理其他交易
                    print(f"准备交易记录时出错: {str(e)}")
                    continue
            
            # 批量插入到数据库
            try:
                self.db.insert_transactions(transaction_data)
                success_count = len(transaction_data)
            except Exception as e:
                # 如果批量插入失败，回退到逐条插入
                print(f"批量插入失败，回退到逐条插入: {str(e)}")
                success_count = 0
                for i, data in enumerate(transaction_data):
                    try:
                        self.db.insert_transaction(*data)
                        success_count += 1
                    except Exception as e:
                        print(f"保存交易记录时出错: {str(e)}")
                        continue
                    
                    # 更新进度
                    progress = int((i + 1) / len(transaction_data) * 100)
                    self.update_progress(progress)
            
            self.status_label.setText(f'导入完成，共保存{success_count}/{len(self.transactions)}条记录')
            if success_count == len(self.transactions):
                QMessageBox.information(self, '导入成功', f'成功导入{len(self.transactions)}条交易记录！')
            else:
                QMessageBox.warning(self, '导入完成', f'成功导入{success_count}条交易记录，{len(self.transactions)-success_count}条记录导入失败。')
            self.accept()
            
        except Exception as e:
            QMessageBox.critical(self, '保存失败', f'保存到数据库时出现错误：\n{str(e)}')
            self.reject()
        # 无论成功与否，都关闭对话框
        self.close()